package com.gitee.attendance.controller;

import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import com.gitee.attendance.entity.User;
import com.gitee.attendance.service.HomeServiceI;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class HomeController {

    private Logger logger = LoggerFactory.getLogger(HomeController.class);

    @Autowired
    private HomeServiceI homeService;

    @RequestMapping("/login")
    public String login(HttpServletRequest request, @RequestParam("file") MultipartFile multipartFile) {
        String result;
        if (multipartFile.isEmpty()) {
            result = "ERROR：上传失败，请选择文件";
        }
        try {
            FileInputStream fis = (FileInputStream) multipartFile.getInputStream();
            result = homeService.faceMatch(fis, request.getParameter(User.USERCODE));
            request.getSession().setAttribute("access_token",result);
        } catch (IOException e) {
            logger.error("ERROR：", e);
            result = "ERROR：文件信息异常";
        } catch (Exception e) {
            logger.error("ERROR：", e);
            result = "ERROR：业务逻辑异常";
        }
        return result;
    }

    @RequestMapping("/attendance")
    public String attendance(HttpServletRequest request, @RequestParam("file") MultipartFile multipartFile)
            throws Exception {
        String userName = request.getParameter(User.USERNAME);
        String userCode = request.getParameter(User.USERCODE);
        FileInputStream fis = (FileInputStream) multipartFile.getInputStream();

        User user = new User();
        user.setUserName(userName);
        user.setUserCode(userCode);
        user.setUserFace(fis);
        String result = homeService.attendance(user);
        logger.info(result);
        return result;
    }
}